package main

import (
	"fmt"
	"strings"
)

const (
	_TRIE_CHILD_LEN = 26
)

type Trie struct {
	Key        byte
	IndexArray []int32
	NextNode   [_TRIE_CHILD_LEN]*Trie
}

func GetNode(ch byte) *Trie {
	node := new(Trie)
	node.Key = ch
	return node
}

func NewTrie() *Trie {
	root := GetNode(' ')
	return root
}

func (root *Trie) InsertStringArray(strs []string) {
	if strs == nil {
		return
	}

	for i, _ := range strs {
		InsertString(strs[i], root, int32(i))
	}
}

func InsertString(str string, root *Trie, pos int32) {
	if l := len(str); l == 0 {
		return
	}
	low := strings.ToLower(str)
	curNode := root

	fmt.Println("keys: ", low)
	for i, _ := range str {
		index := low[i] - 'a'
		if curNode.NextNode[index] == nil {
			curNode.NextNode[index] = GetNode(low[i])
		}
		curNode.NextNode[index].IndexArray = append(curNode.NextNode[index].IndexArray, pos)
		curNode = curNode.NextNode[index]
	}
}

func (node *Trie) TraversalTrie() {
	if node == nil {
		fmt.Println("trie is nil")
		return
	}

	for i := 0; i < _TRIE_CHILD_LEN; i++ {
		if node.NextNode[i] != nil {
			node.NextNode[i].TraversalTrie()
			/*fmt.Println(node.NextNode[i].Key)*/
			fmt.Println(node.NextNode[i].IndexArray)
		}
	}
}

func (root *Trie) SearchTrie(keys string) []int32 {
	if root == nil {
		return nil
	}
	if l := len(keys); l == 0 {
		return nil
	}

	curNode := root
	low := strings.ToLower(keys)
	for i, _ := range low {
		index := low[i] - 'a'
		if curNode.NextNode[index] == nil {
			return nil
		}
		curNode = curNode.NextNode[index]
	}

	retArray := curNode.IndexArray
	fmt.Println("ret array:", retArray)
	return retArray
}
